import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
/**
 * Created with IntelliJ IDEA.
 * User: Anastasia
 * Date: 22.01.15
 * Time: 15:09
 * To change this template use File | Settings | File Templates.
 */
public class LoaderList  extends JFrame implements ActionListener {

    private LoaderList list;
    private ArrayList<Employee>   employees;
    private  JPanel panel ;
    private JComboBox box;

    private JTable table;
    private JLabel label;
    private JLabel label2;

    private JButton editor;         //редактирование сотрудника
    private JButton delete;

    private JLabel sort;

    private JComboBox typesx;
    private int index ;            //byltrc ktvtyn


    private int typeindex;
    private JLabel label3;
    private JButton select;



    private JButton  changer;
    private JLabel dep;
   public LoaderList()
   {
       employees = new ArrayList<Employee>();
       index=-1;
       typeindex =-1;
  changer = new JButton();
       dep = new JLabel();

       select = new JButton();
       label3 = new JLabel();

   }

    public int getIndex()
    {
        return index;
    }

    public Employee getEmployeebyindex()
    {
        return employees.get(index);
    }



    public class Edit  extends JFrame implements ActionListener{


        public class Changer extends Thread implements ActionListener
        {

            public void actionPerformed(ActionEvent arg0)
            {
                try
                {

                    panel.remove(dep);
                    panel.remove(changer);
                     withoutDeparmentbutton = new JButton("Без отдела");
                     withoutDeparmentbutton.setBounds(200,250,200,30);
                    panel.add(withoutDeparmentbutton);

                    withoutDeparmentbutton.addActionListener(new WithoutDepartment());     //добавление обработчика на кнопку без отдела


                     existDepartmentbutton = new JButton("Существуюший отдел");
                      existDepartmentbutton.setBounds(410,250,200,30);
                    panel.add(existDepartmentbutton);

                      existDepartmentbutton.addActionListener(new GetterofDepartment());   //вывод существующих отделов
                    panel.validate();
                    panel.repaint();

                }
                catch (Exception e)
                {
                    System.out.println("init error: " +e); // Print exception

                    e.printStackTrace();
                }



            }
        }

        public class Select extends Thread implements ActionListener     //обработчик на выбор сотрудника;
        {

            public void actionPerformed(ActionEvent arg0)
            {
                try
                {
                    int i=-1;
                    i = box1.getSelectedIndex();

                    Department department1 = departments.get(i);
                    dep  = new JLabel(department1.getInfo());
                    employee2.setDepartment(department1);
                    changer = new JButton("Изменить");
                    changer.setBounds(650, 250, 200, 30);


                    changer.addActionListener(new Changer());
                    panel.add(changer);
                    panel.remove(box1);
                    dep.setBounds(200, 250, 450, 30);
                    panel.add(dep);
                    panel.repaint();
                    panel.validate();

                }
                catch (Exception e)
                {
                    System.out.println("init error: " +e); // Print exception

                    e.printStackTrace();
                }



            }
        }

        public class GetterofDepartment extends Thread implements ActionListener
        {

            public void actionPerformed(ActionEvent arg0)
            {
                try
                {
                    // JOptionPane.showMessageDialog(null,"Список отделов пуст", "Inane error",
                    // JOptionPane.ERROR_MESSAGE);



                    InetAddress addr = InetAddress.getByName(null);
                    Socket socket = new Socket(addr, 8080);

                    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                    out.writeObject(new Exchanger(12,null));
                    //  System.out.println("Ok");

                    out.flush();  //чудный метод.

                    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                    Object object = in.readObject();

                    departments = (ArrayList<Department>)object;



                    if(departments == null||departments.size()==0)
                    {
                        JOptionPane.showMessageDialog(null,"Список отделов пуст", "Error",
                                JOptionPane.ERROR_MESSAGE);


                    }
                    else{

                        panel.remove(withoutDeparmentbutton);
                        panel.remove(existDepartmentbutton);
                        panel.repaint();
                        String info[]= new String[departments.size()];

                        for(int i =0;i< departments.size();i++)
                        {
                            info[i]=departments.get(i).getInfo();
                        }
                        box1 = new JComboBox(info);

                        box1.setBounds(300,250,300,50);
                        box1.setVisible(true);
                        box1.addActionListener(new Select());
                        panel.add(box1);
                        panel.repaint();
                        panel.validate();

                    }

                }

                catch (Exception e)
                {
                    System.out.println("init error: " +e); // Print exception

                    e.printStackTrace();
                }



            }
        }

        public class WithoutDepartment extends Thread implements ActionListener
        {

            public void actionPerformed(ActionEvent arg0)
            {
                try
                {


                    employee2.setDepartment(null);
                    panel.remove(withoutDeparmentbutton);
                    panel.remove(existDepartmentbutton);
                    panel.repaint();

                    changer = new JButton("Изменить");
                    changer.setBounds(450, 250, 200, 30);

                    changer.addActionListener(new Changer());
                    panel.add(changer);
                    if(employee2.getDepartment()==null)
                    {
                        dep = new JLabel("Сотрудник без отдела");
                    }
                    else {dep = new JLabel(employee2.getDepartment().getName());}

                    dep.setBounds(260,250,150,30);
                    panel.add(dep);
                    panel.repaint();
                    panel.validate();


                }

                catch (Exception e)
                {
                    System.out.println("init error: " +e); // Print exception

                    e.printStackTrace();
                }



            }
        }


        public class SendEmployee extends Thread implements ActionListener  {


            public void actionPerformed(ActionEvent arg0)
            {

                try {
                    // Employee employee = new Employee(name.getText(),surname.getText(), lastname.getText(), pay.getText(), phone.getText());


                    employee2.setName(name.getText());
                    employee2.setSurname(surname.getText());
                    employee2.setLastName(lastname.getText());
                    employee2.setPay(pay.getText());
                    employee2.setPhoneNumber(phone.getText());


                    InetAddress addr = InetAddress.getByName(null);



                    Socket socket = new Socket(addr, 8080);

                    // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    Object mas[] = new Object[2];
                    mas[0]=  index;
                    mas[1] =  employee2;

                    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                    out.writeObject(new Exchanger(41,mas));


                    out.flush();
                    //  System.out.println("Ok");


                    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                    Object object = in.readObject();


                    String data = (String)object;

                    if (data.equals("0"))
                    {
                        list.dispose();
                        form.dispose();
                        JOptionPane.showMessageDialog(null,"Изменения сохранены", "OK",
                                JOptionPane.INFORMATION_MESSAGE);

                    }
                    else{
                        if(data.equals("1"))
                        {    JOptionPane.showMessageDialog(null,"Неверное имя сотрудника", "Error",
                                JOptionPane.ERROR_MESSAGE);

                        }
                        if(data.equals("3"))
                        {
                            JOptionPane.showMessageDialog(null,"Неверная фамилия сотрудника", "Error",
                                    JOptionPane.ERROR_MESSAGE);
                        }
                        if(data.equals("2"))
                        {
                            JOptionPane.showMessageDialog(null,"Неверное отчество сотрудника", "Error",
                                    JOptionPane.ERROR_MESSAGE);
                        }

                        if(data.equals("4"))
                        {
                            JOptionPane.showMessageDialog(null,"Неверная зарплата сотрудника", "Error",
                                    JOptionPane.ERROR_MESSAGE);
                        }
                        if(data.equals("5"))
                        {
                            JOptionPane.showMessageDialog(null,"Неверный телефон сотрудника", "Error",
                                    JOptionPane.ERROR_MESSAGE);
                        }

                    }
                    out.close();
                    in.close();
                    socket.close();
                }
                catch (Exception e)
                {
                    System.out.println("init error: " +e); // Print exception

                    e.printStackTrace();
                }

                // dispose();  закрыть окно по кнопке

            }
        }


        private Employee employee;

        private Employee employee2;

        private Employee employee3;  // для обновления

        private Edit form;

        private  ArrayList<Department> departments;

        private JButton button;
        private  JPanel panel = new JPanel();
        private JLabel Label;

        private JComboBox box1;
        private JLabel namelabel= new JLabel("Имя");
        private JLabel surnamelabel= new JLabel("Отчество");
        private JLabel lastnamelabel = new JLabel("Фамилия");
        private JLabel departmentlabel = new JLabel("Департамент");
        private JLabel paylabel = new JLabel("Зарплата");
        private JLabel  phonelabel = new JLabel("Телефон");
        private JTextField name = new JTextField(10);
        private JTextField surname;
        private JTextField lastname;
        private JTextField department;
        private JTextField pay;
        private JTextField phone;
        private JButton withoutDeparmentbutton;
        private JButton existDepartmentbutton;
        private JTextField res;


        public Edit()
        {
            employee = new Employee();
            employee2 = new Employee();
            employee3 = new Employee();
            departments = new ArrayList<Department>();
        }




        public void actionPerformed(ActionEvent arg0)
        {
            if(index!=-1)
            {
                try{

                    employee = employees.get(index);     //взяли из старого списка
                    employee2 = employee;
                    Exchanger exchanger = new Exchanger(index,employee);
                    InetAddress addr = InetAddress.getByName(null);



                    Socket socket = new Socket(addr, 8080);

                    // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                    out.writeObject(new Exchanger(51,exchanger));
                    //  System.out.println("Ok");

                    out.flush();  //чудный метод.


                    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                    Object object = in.readObject();

                    String string = (String)object;





                    if(string.equals("1"))
                    {




                    form = new Edit();

                    form.setVisible(true);
                    form.setBounds(100,100,1000,1000);

                    panel = new JPanel();
                    panel.setLayout(null);
                    res = new JTextField();
                    res.setBounds(100, 30, 400, 30);

                    panel.add(res);
                    res.setVisible(false);


                    namelabel = new JLabel("Имя");
                    namelabel.setBounds(100,100,80,30);
                    panel.add(namelabel) ;

                    name = new JTextField();

                    name.setText(employee.getName());
                    name.setBounds(200, 100, 200, 30);

                    panel.add(name);


                    surnamelabel = new JLabel("Отчество");
                    surnamelabel.setBounds(100,150,80,30);


                    panel.add(surnamelabel) ;

                    surname = new JTextField();
                    surname.setBounds(200, 150, 200, 30);
                     surname.setText(employee.getSurname());
                    panel.add(surname);


                    lastnamelabel = new JLabel("Фамилия");
                    lastnamelabel.setBounds(100,200,80,30);
                    panel.add(lastnamelabel) ;

                    lastname = new JTextField();
                    lastname.setBounds(200, 200, 200, 30);
                    lastname.setText(employee.getLastName());
                    panel.add(lastname);

                    departmentlabel = new JLabel("Департамент");
                    departmentlabel.setBounds(100,250,80,30);
                    panel.add(departmentlabel) ;


                    if(employee.getDepartment()==null)
                    {
                        dep = new JLabel("Сотрудник без отдела");
                    }

                    else{dep = new JLabel(employee.getDepartment().getInfo());}

                    dep.setBounds(200,250,150,30);
                    panel.add(dep);

                    changer = new JButton("Изменить");
                    changer.setBounds(400,250,80,30);
                    panel.add(changer);

                    changer.addActionListener(new Changer());

                    //department = new JTextField();
                    //department.setBounds(200, 250, 200, 30);


                    //    panel.add(department);


                 //   withoutDeparmentbutton = new JButton("Без отдела");
                //    withoutDeparmentbutton.setBounds(200,250,200,30);
                //    panel.add(withoutDeparmentbutton);

                //  withoutDeparmentbutton.addActionListener(new WithoutDepartment());     //добавление обработчика на кнопку без отдела


                 //   existDepartmentbutton = new JButton("Существуюший отдел");
                   // existDepartmentbutton.setBounds(410,250,200,30);
                  //  panel.add(existDepartmentbutton);

               //     existDepartmentbutton.addActionListener(new GetterofDepartment());   //вывод существующих отделов


                    paylabel = new JLabel("Зарплата");
                    paylabel.setBounds(100,300,80,30);
                    panel.add(paylabel) ;

                    pay = new JTextField();
                    pay.setBounds(200, 300, 200, 30);
                   pay.setText(employee.getPay());
                    panel.add(pay);

                    box1 = new JComboBox();
                    box1.setBounds(50,450,200,200);
                    panel.add(box1);
                    box1.setVisible(false);

                    phonelabel = new JLabel("Телефон");
                    phonelabel.setBounds(100,350,80,30);
                    panel.add(phonelabel) ;

                    panel.validate();


                    phone = new JTextField();
                    phone.setBounds(200, 350, 200, 30);
                    phone.setText(employee.getPhoneNumber());
                    panel.add(phone);

                    button = new JButton("Сохранить изменения");            //завершающая.
                    button.setBounds(150,400,200,30);
                    panel.add(button);

                    button.addActionListener(new SendEmployee());

                    form.add(panel);


                    panel.validate();



                    }

                    else
                    {
                        JOptionPane.showMessageDialog(null,"Невозмжно редакировать сотрудника, так как он был изменен или удален", "Error",
                                JOptionPane.ERROR_MESSAGE);

                    }


                }

                catch (Exception e)
                {
                    System.out.println("init error: " +e); // Print exception

                    e.printStackTrace();
                }


            }


            else
            {
                JOptionPane.showMessageDialog(null,"Не выбран сотрудник", "Error",
                        JOptionPane.ERROR_MESSAGE);
            }


        }


    }


    public class Changer extends Thread implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {
                index =-1;


                InetAddress addr = InetAddress.getByName(null);



                Socket socket = new Socket(addr, 8080);

                // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                out.writeObject(new Exchanger(3,null));
                //  System.out.println("Ok");

                out.flush();  //чудный метод.


                ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                Object object = in.readObject();

                employees = (ArrayList<Employee>)object;

                if(employees == null||employees.size()==0)
                {
                    JOptionPane.showMessageDialog(null,"Список сотрудников пуст", "Error",
                            JOptionPane.ERROR_MESSAGE);


                }
                else{

                String info[]= new String[employees.size()];

                for(int i =0;i< employees.size();i++)
                {
                    info[i]=employees.get(i).getInfo();
                }
                box = new JComboBox(info);
                box = new JComboBox(info);



                box.setBounds(50,100,300,50);
                box.setVisible(true);
                box.addActionListener(new Selector());

                    String columnsnames[]= {"Имя", "Фамилия", " Отчество", "Отдел", "Зарплата","Телефон"};
                    String info1 [][] = new String [employees.size()][] ;

                    for (int i =0;i<employees.size();i++)
                    {

                        info1[i] = new String[6];
                        info1[i][0] = employees.get(i).getName();
                        info1[i][1] = employees.get(i).getSurname();
                        info1[i][2] = employees.get(i).getLastName();

                        if(employees.get(i).getDepartment()==null)
                        {
                            info1[i][3] = "сотрудник без отдела";

                        }
                        else
                        {
                            info1[i][3] = employees.get(i).getDepartment().getName();

                        }

                        info1[i][4] = employees.get(i).getPay();
                        info1[i][5] = employees.get(i).getPhoneNumber();


                    }

                    table = new JTable(info1, columnsnames);

                    JScrollPane scrollPane = new JScrollPane(table);

                    panel.add(scrollPane);

                    scrollPane.setViewportView(table);
                    scrollPane.setVisible(true);


                    //  scrollPane.getViewport().add(table);

                    ListSelectionModel selModel = table.getSelectionModel();

                    selModel.addListSelectionListener(new SelectorTable());

                    table.setBounds(10,100,500,200);

                    panel.remove(select);
                panel.remove(label3);

               panel.add(table);


                panel.validate();
                panel.repaint();
                }

            }
            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }

    public class Selector extends Thread implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {

               index = box.getSelectedIndex();

                panel.remove(box);

                label3 = new JLabel(employees.get(index).getInfo());
                label3.setBounds(20,100,300,50);

                panel.add(label3);

                select = new JButton("Изменить");
                select.setBounds(350,100,100,30);
                panel.add(select);
                select.addActionListener(new Changer());

                panel.repaint();
                panel.validate();


            }

            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }



    public class TypeSelector extends Thread implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {

               typeindex = typesx.getSelectedIndex();

                InetAddress addr = InetAddress.getByName(null);


                Exchanger exchanger1 = new Exchanger(typeindex,null);
                Socket socket = new Socket(addr, 8080);

                // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                out.writeObject(new Exchanger(55,exchanger1));
                //  System.out.println("Ok");

                out.flush();  //чудный метод.


                ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                Object object = in.readObject();

                employees = (ArrayList<Employee>)object;

                if(employees == null||employees.size()==0)
                {
                    JOptionPane.showMessageDialog(null,"Список сотрудников пуст", "Error",
                            JOptionPane.ERROR_MESSAGE);

                    list.dispose();


                }
                else{




                    String columnsnames[]= {"Имя", "Фамилия", " Отчество", "Отдел", "Зарплата","Телефон"};
                    String info1 [][] = new String [employees.size()][] ;

                    for (int i =0;i<employees.size();i++)
                    {
                        info1[i] = new String[6];
                        info1[i][0] = employees.get(i).getName();
                        info1[i][1] = employees.get(i).getSurname();
                        info1[i][2] = employees.get(i).getLastName();

                        if(employees.get(i).getDepartment()==null)
                        {
                            info1[i][3] = "без отдела";

                        }
                        else
                        {
                            info1[i][3] = employees.get(i).getDepartment().getName();

                        }

                        info1[i][4] = employees.get(i).getPay();
                        info1[i][5] = employees.get(i).getPhoneNumber();


                    }


                    panel.remove(table);

                   panel.remove(label3) ;
                    panel.remove(select);

                    table = new JTable(info1, columnsnames);
                    table.setBounds(10,100,500,200);
                    //JScrollPane scrollPane = new JScrollPane(table);

                    //scrollPane.setViewportView(table);
                    //scrollPane.setVisible(true);
                    ListSelectionModel selModel = table.getSelectionModel();

                    selModel.addListSelectionListener(new SelectorTable());

                   // panel.add(scrollPane);

                    panel.add(table);

                    panel.repaint();
                    panel.validate();


                }


                    //  panel.remove(box);
              //



            }

            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }



    public class SelectorTable extends Thread implements  ListSelectionListener
    {

        public void valueChanged(ListSelectionEvent e)
        {
            try
            {

                index = table.getSelectedRow();

                panel.remove(table);

                label3 = new JLabel(employees.get(index).getInfo());
                label3.setBounds(20,100,300,50);

                panel.add(label3);

                select = new JButton("Изменить");
                select.setBounds(350,100,100,30);
                panel.add(select);
                select.addActionListener(new Changer());

                panel.repaint();
                panel.validate();


            }

            catch (Exception exc)
            {
                System.out.println("init error: " +exc); // Print exception

                exc.printStackTrace();
            }



        }
    }





    public void actionPerformed(ActionEvent arg0)
    {
           try{




        InetAddress addr = InetAddress.getByName(null);



        Socket socket = new Socket(addr, 8080);

        // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
        out.writeObject(new Exchanger(3,null));
        //  System.out.println("Ok");

        out.flush();  //чудный метод.


        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
        Object object = in.readObject();

        employees = (ArrayList<Employee>)object;


               if(employees == null||employees.size()==0)
               {
                   JOptionPane.showMessageDialog(null,"Список сотрудников пуст", "Error",
                           JOptionPane.ERROR_MESSAGE);


               }
               else{

                   list = new LoaderList();

                   panel = new JPanel() ;
                   panel.setLayout(null);
                   list.setVisible(true);
                   list.setBounds(100, 100, 500, 500) ;

                    String columnsnames[]= {"Имя", "Фамилия", " Отчество", "Отдел", "Зарплата","Телефон"};
                   String info1 [][] = new String [employees.size()][] ;

                   for (int i =0;i<employees.size();i++)
                   {
                       info1[i] = new String[6];
                      info1[i][0] = employees.get(i).getName();
                       info1[i][1] = employees.get(i).getSurname();
                       info1[i][2] = employees.get(i).getLastName();

                       if(employees.get(i).getDepartment()==null)
                       {
                           info1[i][3] = "сотрудник пока что без отдела";

                       }
                       else
                       {
                           info1[i][3] = employees.get(i).getDepartment().getName();

                       }

                       info1[i][4] = employees.get(i).getPay();
                       info1[i][5] = employees.get(i).getPhoneNumber();


                   }

                   table = new JTable(info1, columnsnames);
                   table.setBounds(10,100,500,200);
                   JScrollPane scrollPane = new JScrollPane(table);

                   scrollPane.setViewportView(table);
                   scrollPane.setVisible(true);


                   panel.add(scrollPane);

                 //  scrollPane.getViewport().add(table);

                   table.setBounds(50,100,300,200);


                  /* String info[]= new String[employees.size()];

                   for(int i =0;i< employees.size();i++)
                   {
                       info[i]=employees.get(i).getInfo();
                   }
                   box = new JComboBox(info);   */

                   label = new JLabel("Список сотрудников:");
                   label.setBounds(10,50,200,30);
                   panel.add(label);

                   label2 = new JLabel("Выберите сотрудника для действия с ним") ;
                   label2.setBounds(220,50,250,30);
                   panel.add(label2);

                   table.setBounds(10,100,500,200);
                   table.setVisible(true);


                   ListSelectionModel selModel = table.getSelectionModel();

                  selModel.addListSelectionListener(new SelectorTable());



                           //   box.setBounds(50,100,300,50);
                //   box.setVisible(true);
               //    box.addActionListener(new Selector());

                   String types []= {"фамилии", "имени", "отчеству", "зарплате"};
                   editor = new JButton("Редактировть запись");
                   editor.setBounds(30,300,150,30);
                   panel.add(editor);


                   editor.addActionListener(new Edit());
                   delete = new JButton("Удалить запись");
                   delete.setBounds(190, 300, 150, 30);
                   panel.add(delete);

                   sort = new JLabel("Сортировать список по ");
                   sort.setBounds(30,340,150,30);
                   panel.add(sort);

                   typesx = new JComboBox(types);
                   typesx.setBounds(200,340,150,50);
                   panel.add(typesx);

                    typesx.addActionListener(new TypeSelector());


                   panel.add(table);
                   panel.repaint();
                   panel.validate(); //list.add(scrollPane);
                   list.add(panel);

                  // box1.setPreferredSize(new Dimension(500, 800));
               }





           }
           catch (Exception e)
           {
               System.out.println("init error: " +e); // Print exception

               e.printStackTrace();
           }
    }
}
